/**
* @file         
* @brief		顺序栈，数组方式.
* @details	    基本功能演示.
* @author		conkty@126.com
* @date		    2023
* @version	    v0.1
* @par 更新记录:         
*	v0.1: 初建\n
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static const unsigned int MAX_SIZE = 3;

typedef struct ElemType {
    int id;
    float value;
} Node;

typedef struct stack_array {
    Node data[3];
    // 注意此处不再使用unsigned，因索引相减可能为负.
    int top; // 栈顶位置
} Stack;

void initial(Stack* s) {
    // 全部内容初始化为空(0)
    memset(s->data, 0, MAX_SIZE * sizeof(Node));
    // 初始化栈顶栈底位置
    s->top = 0;
}

int push(Stack* s, Node* e) {
    if (s->top >= MAX_SIZE) {
        printf("stack is full, push failed, id is %d .\n", e->id);
        return -1;
    }

    printf("pushing node with id %d ...\n", e->id);
    s->data[s->top++] = *e;

    return 0;
}

Node* pop(Stack* s) {
    if(0 == s->top) {
        printf("stack is empty, pop faild.\n");
        return NULL;
    }

    // Node *e = &s->data[--s->top];
    Node *e = s->data+(--s->top);
    printf("node %d is poped.\n", e->id);

    return e;
}

Node* top(Stack* s) {
    if(0 == s->top) {
        printf("stack is empty, pop faild.\n");
        return NULL;
    }

    return s->data+(s->top-1);
}

void traverse(Stack* s) {
    printf("top %d bottom %d\n", s->top, 0);
    printf("size %d\n", s->top);
    for (int i = 0; i < s->top; ++i) {
        printf("%d ", s->data[i].id);
    }
    printf("\n");
}

void pop_test(Stack* s) {
    Node *e = pop(s);
    if(NULL != e) {
        printf("succeed to pop %d\n", e->id);
    } else {
        printf("faild to pop.\n");
    }
}

void top_test(Stack* s) {
    Node *e = top(s);
    if(NULL != e) {
        printf("succeed to get top %d\n", e->id);
    } else {
        printf("faild to get top.\n");
    }
}


int main()
{
    Stack s;
    initial(&s);
    traverse(&s);

    Node a0 = {10, 0.0};
    Node a1 = {11, 0.0};
    Node a2 = {12, 0.0};
    Node a3 = {13, 0.0};
    push(&s, &a0);
    push(&s, &a1);
    push(&s, &a2);
    push(&s, &a3);
    traverse(&s);

    pop_test(&s);
    traverse(&s);

    top_test(&s);

    return 0;
}
